package com.bingquan.company.optional;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.junit.Assert.assertEquals;

public class OptionalTest {


    @Test
    public void test() {
        User user = null;
        User user2 = new User("anna@gmail.com", "1234");
        /**
         *  ofNullable(user) 为空， 则返回 orElse(user2)
         *
         */
        User result = Optional.ofNullable(user).orElse(user2);
        assertEquals(user2.getEmail(), result.getEmail());

    }

    @Test
    public void test02() {
        /**
         * ifPresent  结合lamda 表达式， 可以完美规避空指针
         */
        User user = new User("john@gmail.com", "1234");
        Optional<User> opt = Optional.ofNullable(user);
        opt.ifPresent(u -> assertEquals(user.getEmail(), u.getEmail()));

    }

    @Test
    public void test03() {
        /**
         *  ofNullable(list) 为空， 则返回 orElse(Collections.emptyList()) 也是空集合
         *  Optional.ofNullable(list).orElse(Collections.emptyList())  为空， 也可以stream().forEach()操作
         */
        List<String> list = new ArrayList<>();
        Optional.ofNullable(list).orElse(Collections.emptyList()).stream().forEach(var -> {
            System.out.println("===" + var);
        });
        System.out.println("+++");

    }

}
